package com.dsx.haha.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author dsx
 * @date 2021/3/8 17:16
 * @since JDK1.8
 */
@Configuration
public class ShiroConfig {


    //获取ShiroFilterFactoryBean对象    3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager webSecurityManager) {
        System.out.println("1111111111111");
        ShiroFilterFactoryBean shiroFilterBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterBean.setSecurityManager(webSecurityManager);
        /*
        shiro的内置过滤器
            第一个参数是请求路径，requestMapping("路径")
            anon: 无需认证就可以访问
            authc： 认证才能访问
            user： 必须拥有记住我才能访问
            perms： 拥有某个资源的权限才能访问
            role：拥有某个角色的权限才能访问 
         */
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        System.out.println("22222222222222222222");
        //拦截，没有认证（登录）不能访问，如果没有认证默认跳转到登录界面
        
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/index", "anon");
        //用户，需要角色权限 “user”
        //filterChainDefinitionMap.put("/user/**", "roles[user]");//数据库中字段属性是user
        //开放登陆接口
        filterChainDefinitionMap.put("/tenant/tologin", "anon");
        filterChainDefinitionMap.put("/tenant/login", "anon");
        filterChainDefinitionMap.put("/tenant/toregist", "anon");
        filterChainDefinitionMap.put("/tenant/addtenant", "anon");
        filterChainDefinitionMap.put("/noauth", "anon");
        //其余接口一律拦截        
        //该这行代码必须放在所有权限设置的最后，不然会导致所有 url 都被拦截
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        
        shiroFilterBean.setLoginUrl("/tenant/tologin");
        shiroFilterBean.setUnauthorizedUrl("/tenant/noauth");
        return shiroFilterBean;
    }
    @Bean
    public UserRealm getUserRealm(){
        return new UserRealm();
    }
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getUserRealm") UserRealm userRealm){
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        webSecurityManager.setRealm(userRealm);
        return webSecurityManager;
    }

    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
    
}
